import os
from fastapi import FastAPI, Request, Depends, applications
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from server.api import router

from server.exceptions import CustomException

from dotenv import load_dotenv
from server.middleware.log import logger

load_dotenv('.env')
env = os.getenv("ENV", "local")
version = os.getenv('VERSION', '0.1.0')


def init_routers(app_: FastAPI) -> None:
    app_.include_router(router)


def init_listeners(app_: FastAPI) -> None:
    # Exception handler
    @app_.exception_handler(CustomException)
    def custom_exception_handler(request: Request, exc: CustomException):
        return JSONResponse(
            status_code=exc.code,
            content={"error_code": exc.error_code, "message": exc.message},
        )


def create_app() -> FastAPI:
    app_ = FastAPI(
        title="Alpha agent Svc",
        description="Alpha agent chat",
        version=version,
        docs_url=None,
        redoc_url=None,
    )

    app_.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],  # 允许所有 HTTP 方法
        allow_headers=["*"],  # 允许所有 HTTP 头部
    )

    init_routers(app_=app_)
    init_listeners(app_=app_)
    logger.info("=======================================================")
    logger.info(f"======= alpha agent svc@{version} {{{env}}} start =======")
    logger.info("=======================================================")
    return app_


app = create_app()
